<?php

namespace App\Tenancy\Controllers;

use App\Models\ArticleModel;
use App\Models\AudioStudy;
use App\Models\BookModel;
use App\Models\BookPermission;
use App\Models\WorkModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Auth;

class AudioStudyController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '音频学习';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new AudioStudy());
        $admin = Auth::guard('admin')->user()->toArray();
        $grid->model()->where('company_id', '=',$admin['company_id']);

        $grid->column('id', __('Id'));
        $grid->column('title', '标题');
        $grid->column('book_id', '书本')->display(function($book_id) {
            return BookModel::find($book_id)->book_title;
        });

        $grid->column('created_at', '创建时间');
        $grid->column('updated_at','更新时间');

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(AudioStudy::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('title', '标题');
        $show->field('book_id', '书本')->as(function ($book_id) {

            return BookModel::find($book_id)->book_title;

        });
        $show->field('created_at', '创建时间');
        $show->field('updated_at','更新时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new AudioStudy());

        $company_id = Auth::guard('admin')->user()->company_id;
        if(!empty($company_id)){
            $book_ids_1 = BookModel::where('opend_type',1)->pluck('id')->toArray();
            //查出专属书本
            $book_ids_2 = BookPermission::where('company_id',$company_id)->pluck('book_id')->toArray();
            $book_ids = array_keys(array_flip($book_ids_1)+array_flip($book_ids_2));
        }

        $form->text('title', '标题');
        $form->select('book_id', '书本')->options(
            BookModel::whereIn('id',$book_ids)->pluck('book_title','id')
        )->load('article_id','/admin/book_article');

        $form->hasMany('many_audio_article','章节安排',function (Form\NestedForm $form) {

            $form->select('article_id','文章')->options(
                ArticleModel::/*whereIn('type',[1,2])->*/pluck('article_title','id')
            );

        });

        $form->hidden('company_id','公司');

        //保存前回调
        $form->saving(function (Form $form) {
            $admin = Auth::guard('admin')->user()->toArray();
            $form->company_id = $admin['company_id'];
            //dd($form->company_id);
        });

        return $form;
    }
}
